home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 6909 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.arch.arithmetic,comp.lang.c,comp.lang.c++
  4. Subject: Re: Access carry flag from C
  5. Date: Tue, 20 Feb 96 21:54:32 GMT
  6. Organization: none
  7. Message-ID: <824853272snz@genesis.demon.co.uk>
  8. References: <Dn1C9z.DGv.0.net@indra.com> <ARTHUR.96Feb20143404@gold.Smallworld.co.uk>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <ARTHUR.96Feb20143404@gold.Smallworld.co.uk>
  15.            arthur@Smallworld.co.uk "Arthur Chance" writes:
  16.  
  17. >In article <31298D20.41C6@bazis.nl> Franz Korntner <fkorntne@bazis.nl> writes:
  18. >> j+k will overflow when the result exceeds MAXINT
  19. >> 
  20. >> Thus:  "if (j+k > MAXINT) overflow();" but the operation is undefined
  21. >> if the result overflows, so the expression needs rewriting to make sure
  22. >> this doesn't happen. The result is then "if (j>MAXINT-k) overflow();".
  23. >
  24. >As we must be talking about signed ints, because unsigned can't cause
  25. >undefined behaviour by overflow, if k < 0, then MAXINT-k overflows.
  26. >
  27. >Basically, the C *standard* is useless on things like signed overflow
  28. >(or word size, or what happens with right shift of -ve numbers, or
  29. ><insert your favourite "undefined behaviour" gripe here>). You have
  30. >to look carefully at each *implementation* you use. You can usually
  31. >find some way to do what you want, but you have to accept it's never,
  32. >ever going to be standard C.
  33.  
  34. It certainly can be done portably although not with the efficiency that
  35. a platform-specific solution is likely to give you.
  36.  
  37.     int j, k;
  38.  
  39.     ...
  40.  
  41.     if ((j >= 0) ? (k > INT_MAX-j) : (k < INT_MIN-j))
  42.        ...
  43.  
  44. will test if j+k overflows. You have to perform the test before doing the
  45. calculation since if j+k overflows the result is undefined behaviour
  46. whatever you do afterwards.
  47.  
  48. -- 
  49. -----------------------------------------
  50. Lawrence Kirby | fred@genesis.demon.co.uk
  51. Wilts, England | 70734.126@compuserve.com
  52. -----------------------------------------
  53.